// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#pragma once

#include <iomanip>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

#include "coin2/base/time.h"
#include "coin2/exchange/base/api_base/asio_http_context.h"
#include "coin2/exchange/base/api_base/base_auth.h"
#include "coin2/exchange/base/api_util/api_signature.h"
#include "coin2/exchange/base/api_util/auth_key.h"
#include "coin2/exchange/base/api_util/json_writer.h"
#include "coin2/exchange/base/api_util/url_params_builder.h"

class KucoinBaseAuth {
 public:
  virtual ~KucoinBaseAuth() = default;
};

class KucoinWsAuth : public KucoinBaseAuth {
 public:
  explicit KucoinWsAuth(const std::string& key_filepath)
      : key_(AuthKey::FromFile(key_filepath)) {
  }

 protected:
  AuthKey key_;
};

class KucoinRestAuth : public KucoinBaseAuth, public BaseRestAuth {
 public:
  explicit KucoinRestAuth(
      const std::string& key_filepath,
      const std::string& host,
      const std::string& port,
      const std::string& bind_ip)
      : key_(AuthKey::FromFile(key_filepath)), host_(host), port_(port), bind_ip_(bind_ip) {
  }
  explicit KucoinRestAuth(
      const std::string& key_filepath,
      const std::string& host,
      int32_t port,
      const std::string& bind_ip)
      : key_(AuthKey::FromFile(key_filepath)), host_(host), port_(std::to_string(port)),
          bind_ip_(bind_ip) {
  }

  std::string GetSignature(const std::string& secret_key,
      const std::string& timestamp, const std::string& method,
      const std::string& url_path, const std::string& body) const {
    if (secret_key.empty()) {
      throw std::runtime_error("[Kucoin] Secret key is required");
    }
    std::string cred = timestamp + method + url_path + body;
    return ApiSignatureUtil::GetSignatureByHmacSHA256(cred, secret_key);
  }

  std::string GetPassPhrase(const std::string& secret_key,
      const std::string& pass_phrase) const {
    if (secret_key.empty()) {
      throw std::runtime_error("[Kucoin] Secret key is required");
    }
    return ApiSignatureUtil::GetSignatureByHmacSHA256(pass_phrase, secret_key);
  }

  std::vector<std::pair<std::string, std::string>> GetHeaderSet(
      const std::string& method,
      const std::string& url_path,
      const std::string& body) const {
    std::vector<std::pair<std::string, std::string>> out;
    std::string timestamp = std::to_string((int64_t)(GetCurrentTimestamp() / 1e6));
    std::string signa =
        GetSignature(key_.secret_key(), timestamp, method, url_path, body);
    std::string pass_phrase =
        GetPassPhrase(key_.secret_key(), key_.GetValue("passphrase").value());
    std::string api_key_ver = "2";
    out.push_back(std::make_pair("KC-API-KEY", key_.access_key()));
    out.push_back(std::make_pair("KC-API-SIGN", signa));
    out.push_back(std::make_pair("KC-API-TIMESTAMP", timestamp));
    out.push_back(std::make_pair("KC-API-PASSPHRASE", pass_phrase));
    out.push_back(std::make_pair("KC-API-KEY-VERSION", api_key_ver));
    return out;
  }

  AsioHttpContext* CreateRequestByGetWithSignature(
      const std::string& url_path,
      UrlParamsBuilder* builder) override {
    std::string query_string = builder->ComputeQueryString();
    std::string post_body = builder->ComputePostBody();
    CHECK(post_body.empty());
    std::string target = url_path;
    if (!query_string.empty()) {
      target += "?" + query_string;
    }

    return AsioHttpContext::NewGet(host_, port_, bind_ip_, target,
        GetHeaderSet("GET", target, ""));
  }

  AsioHttpContext* CreateRequestByPostWithSignature(
      const std::string& url_path,
      UrlParamsBuilder* builder) override {
    std::string query_string = builder->ComputeQueryString();
    CHECK(query_string.empty());
    std::string post_body = builder->ComputePostBody();
    std::string target = url_path;
    if (!query_string.empty()) {
      target += "?" + query_string;
    }

    return AsioHttpContext::NewPost(host_, port_, bind_ip_, target,
        GetHeaderSet("POST", url_path, post_body), post_body);
  }

  AsioHttpContext* CreateRequestByDeleteWithSignature(
      const std::string& url_path,
      UrlParamsBuilder* builder) override {
    std::string query_string = builder->ComputePostBodyAsQueryString();
    std::string post_body = builder->ComputePostBody();
    std::string target = url_path;
    if (!query_string.empty()) {
      target += "?" + query_string;
    }

    return AsioHttpContext::NewDelete(host_, port_, bind_ip_, target,
        GetHeaderSet("DELETE", target, ""), "");
  }

  AsioHttpContext* CreateRequestByPutWithSignature(
      const std::string& address,
      UrlParamsBuilder* builder) override {
    return nullptr;
  }

 protected:
  AuthKey key_;
  std::string host_;
  std::string port_;
  std::string bind_ip_;
};
